package com.example.demo.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.entity.Menu;
import com.example.demo.entity.Result;
import com.example.demo.service.MenuService;
import com.example.demo.utils.JWTUtil;
import com.example.demo.utils.MenuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.alibaba.druid.sql.ast.ClusteringType.Hash;

/**
 * 菜单管理
 */
@RestController
@RequestMapping("sys/menu")
public class MenuController {
    @Autowired
    private MenuService menuService;

    @RequestMapping("getMenu")
    public Result getMenu(@RequestParam Map<String,Object> params,HttpServletRequest request){
        String token = request.getHeader("token");
        DecodedJWT tokenInfo = JWTUtil.getTokenInfo(token);
        String account = tokenInfo.getSubject();
        Map<String, Object> map1 = new HashMap<>();
        //获取所有菜单数据
        if(params.get("allFlag")==null||params.get("allFlag").toString().equals("")){
            map1.put("account",account);
        }
        List<Menu> list= menuService.getMenu(map1);
        if(list.size()>0){
            list.stream()
                    .forEach(it->{
                        Map<String,Object> map=new HashMap<String,Object>();
                        map.put("title",it.getCnName());
                        it.setMeta(map);
                    });
        }
        List<Menu> menus = MenuUtil.generateMenu(list);
        List<Menu> menus1 = MenuUtil.getMenus(menus);
        return Result.ok(menus1);
    }

    @GetMapping("getMenuInfo")
    public Result getMenuInfo(@RequestParam Map<String,Object> params){
        return menuService.getMenuInfo(params);
    }

    @PostMapping("insertMenu")
    public Result insertMenu(@RequestBody Map<String,Object> params){
        return menuService.insertMenu(params);
    }

    @PostMapping("updateMenu")
    public Result updateMenu(@RequestBody Map<String,Object> params){
        return menuService.updateMenu(params);
    }

    @PostMapping("insertRoleMenu")
    public Result insertRoleMeun(@RequestBody Map<String,Object> params){
        return menuService.insertRoleMeun(params);
    }
    @GetMapping("getRoleMenuId")
    public Result getRoleMenuId(@RequestParam Map<String,Object> params){
        return menuService.getRoleMenuId(params);
    }
}
